package com.ars.flight;

import com.ars.db.DBTools;
import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;

import javax.swing.*;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AddFlightController {
    @FXML
    private TextField tfScheduleName;
    @FXML
    private TextField tfDiscount;
    @FXML
    private DatePicker dpDate;

    //数据库所需
    private String scheduleName;
    private String discount;
    private String date;
    private int firstSeats;
    private int businessSeats;
    private int economySeats;
    private int scheduleId;

    @FXML
    public void addButtonAction() {
        if(this.getFormValue()) {
            this.updateDB();
            JOptionPane.showMessageDialog(null,"操作成功！");
        }else{
            JOptionPane.showMessageDialog(null,"请将表单填写完整！");
        }
    }

    @FXML
    public void cancelButtonAction() {
        tfDiscount.clear();
        tfScheduleName.clear();
    }

    //获取表单数据
    private boolean getFormValue() {
        scheduleName = tfScheduleName.getText();
        discount = tfDiscount.getText();
        date = (dpDate.getValue() != null) ? dpDate.getValue().toString() : "";
        return !(scheduleName.isEmpty() || discount.isEmpty() || date.isEmpty());
    }

    //获取数据库数据
    private void getValuesFromDB() {
        String sql = "SELECT sid, first_seats, business_seats, economy_seats FROM SCHEDULE,	plane WHERE	`schedule`.pid = plane.pid AND plane.pid = (SELECT SCHEDULE .pid FROM `schedule` WHERE `name` = '" + scheduleName + "')";
        System.out.println(sql);
        ResultSet rs = new DBTools().query(sql);
        try {
            if (rs.next()) {
                this.scheduleId = rs.getInt("sid");
                this.firstSeats = rs.getInt("first_seats");
                this.businessSeats = rs.getInt("business_seats");
                this.economySeats = rs.getInt("economy_seats");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //更新数据库
    private void updateDB() {
        this.getValuesFromDB();
        String sql = "INSERT INTO flight VALUES(NULL," + firstSeats + "," + businessSeats + "," + economySeats + "," + discount + ",'" + date + "'," + scheduleId + ");";
        System.out.println(sql);
        new DBTools().update(sql);
    }
}
